<template>
  <view class="login-container">
    <!-- 顶部切换按钮 -->
    <view class="switch-tab">
      <view class="tab-item" :class="{ active: isLogin }" @click="switchTab(true)">登录</view>
      <view class="tab-item" :class="{ active: !isLogin }" @click="switchTab(false)">注册</view>
    </view>

    <!-- 登录/注册表单 -->
    <view class="form-container">
      <view class="input-item">
        <input
          type="text"
          v-model="formData.username"
          placeholder="请输入用户名/手机号"
          maxlength="20"
        />
      </view>
      <view class="input-item">
        <input
          :type="passwordVisible ? 'text' : 'password'"
          v-model="formData.password"
          placeholder="请输入密码"
          maxlength="20"
        />
        <view class="eye-icon" @click="togglePasswordVisible">
          <image v-if="passwordVisible" src="/static/icon/eye-fill.png" class="icon-img" />
          <image v-else src="/static/icon/eye-close-fill.png" class="icon-img" /> <!-- 假设文件名或路径已调整 -->
        </view>
      </view>
      <!-- 注册时显示确认密码 -->
      <view class="input-item" v-if="!isLogin">
        <input
          :type="confirmPasswordVisible ? 'text' : 'password'"
          v-model="formData.confirmPassword"
          placeholder="请再次输入密码"
          maxlength="20"
        />
        <view class="eye-icon" @click="toggleConfirmPasswordVisible">
          <!-- 使用与主要密码框相同的图标结构 -->
          <image v-if="confirmPasswordVisible" src="/static/icon/eye-fill.png" class="icon-img" />
          <image v-else src="/static/icon/eye-close-fill.png" class="icon-img" /> <!-- 假设文件名或路径已调整 -->
        </view>
      </view>

      <!-- 登录/注册按钮 -->
      <button class="submit-btn" @click="handleAction">{{ isLogin ? '登录' : '注册' }}</button>

      <view class="link" v-if="isLogin" @click="goToForgotPassword">
        忘记密码？
      </view>
    </view>

    <!-- 第三方登录 (可选) -->
    <view class="third-party-login" v-if="isLogin">
      <view class="line"></view>
      <text class="or-text">其他登录方式</text>
      <view class="line"></view>
    </view>
    <view class="third-party-icons" v-if="isLogin">
      <view class="icon-wrapper">
        <text>敬请期待</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
		isLogin: true, 
		passwordVisible: false,
		confirmPasswordVisible: false,
		formData: {
			username: '',
			password: '',
			confirmPassword: '' 
		}
    };
  },
  methods: {
    switchTab(login) {
		this.isLogin = login;
		this.formData = {
			username: '',
			password: '',
			confirmPassword: ''
		};
		this.passwordVisible = false;
		this.confirmPasswordVisible = false;
    },
    togglePasswordVisible() {
		this.passwordVisible = !this.passwordVisible;
    },
    toggleConfirmPasswordVisible() {
		this.confirmPasswordVisible = !this.confirmPasswordVisible;
    },
    async handleAction() {
        const { username, password, confirmPassword } = this.formData;
    
        if (!username || !password) {
			uni.showToast({
              title: '请输入用户名和密码',
              icon: 'none'
            });
            return;
        }
    
          // 显示加载提示，提升用户体验
        uni.showLoading({
            title: this.isLogin ? '登录中...' : '注册中...',
            mask: true
        });
    
        try {
            let response;
            if (!this.isLogin) { 
				if (password !== confirmPassword) {
					uni.hideLoading(); 
					uni.showToast({
						title: '两次输入的密码不一致',
						icon: 'none'
					});
					return;
				}
            // 调用注册API
            response = await uni.request({
                url: 'http://localhost:8080/api/register', 
                method: 'POST',
                data: {
					username: username,
					password: password
                },
                header: {
					'Content-Type': 'application/json'
                }
              });
            } else { 
              // 调用登录API
              response = await uni.request({
                url: 'http://localhost:8080/api/login', 
                method: 'POST',
                data: {
                  username: username,
                  password: password
                },
                header: {
                  'Content-Type': 'application/json'
                }
              });
            }
    
            // 隐藏加载提示
            uni.hideLoading();
    
            const resData = response.data;
    
            // 假设后端成功响应的状态码为 200 或 201，且 success 字段为 true
            // 请根据您的后端实际响应格式调整判断逻辑
            if (resData && (resData.code === 200 || resData.code === 201) && resData.success) { // 示例判断条件
				uni.showToast({
					title: this.isLogin ? '登录成功' : '注册成功',
					icon: 'success'
				});
    
            if (this.isLogin) {
                // 登录成功：保存 token (如果后端返回了 token)
                // 示例：uni.setStorageSync('token', resData.data.token); // 假设 token 在 resData.data.token
                // 跳转到首页
                setTimeout(() => { 
					uni.switchTab({
						url: '/pages/index/index'
					});
                }, 1000);
            } else {
                // 注册成功：清空表单并切换到登录页
                this.formData = {
					username: '',
					password: '',
					confirmPassword: ''
                };
                this.switchTab(true);
              }
            } else {
              // 后端返回失败信息
				uni.showToast({
					title: resData.message || (this.isLogin ? '登录失败' : '注册失败'), // 使用后端返回的错误信息或默认信息
					icon: 'none'
				});
            }
        } catch (error) {
            // 隐藏加载提示
            uni.hideLoading();
    
            console.error('API Error:', error);
            // 处理网络错误或其他异常
            let errorMessage = '网络错误或服务器异常';
            if (error.errMsg) {
				if (error.errMsg.includes('request:fail')) {
					errorMessage = '网络请求失败，请检查网络';
				} else if (error.errMsg.includes('timeout')) {
					errorMessage = '请求超时，请稍后重试';
				}
            }
            uni.showToast({
				title: errorMessage,
				icon: 'none'
            });
          }
        },
    goToForgotPassword() {
		uni.navigateTo({ url: '/pages/commingsoon/commingsoon' });
		console.log('跳转到忘记密码页面');
    }
  }
};
</script>

<style>
/* page 全局样式 */
page {
  background-color: #f5f5f5;
  height: 100%;
}

/* 登录容器 */
.login-container {
  padding: 40rpx;
  box-sizing: border-box;
  height: 100%;
}

/* 顶部切换按钮 */
.login-container .switch-tab {
  display: flex;
  background-color: #e0e0e0;
  border-radius: 50rpx;
  padding: 6rpx;
  margin-bottom: 80rpx;
}

.login-container .switch-tab .tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 32rpx;
  color: #666;
  border-radius: 50rpx;
  transition: all 0.3s ease;
}

.login-container .switch-tab .tab-item.active {
  background-color: #fff;
  color: #007AFF;
  font-weight: bold;
}

/* 表单容器 */
.login-container .form-container {
  /* 内部样式已展开 */
}

.login-container .form-container .input-item {
  position: relative;
  margin-bottom: 40rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 0 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex; /* 添加flex布局 */
  align-items: center; /* 垂直居中对齐 */
}

.login-container .form-container .input-item input {
  height: 80rpx;
  width: calc(100% - 50rpx); /* 减去眼睛图标的宽度和一些内边距 */
  font-size: 28rpx;
  padding-right: 10rpx; /* 为图标留出一点空间 */
}

.login-container .form-container .input-item .eye-icon {
  width: 50rpx; /* 设置图标容器宽度 */
  height: 80rpx; /* 与input同高 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container .form-container .input-item .icon-img {
  width: 36rpx; /* 图标大小 */
  height: 36rpx;
}

.login-container .form-container .submit-btn {
  width: 100%;
  height: 80rpx;
  background-color: #007AFF;
  color: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  margin-top: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
}

.login-container .form-container .submit-btn:active {
  background-color: #0062cc; /* 按下效果 */
}

.login-container .form-container .link {
  text-align: right;
  font-size: 28rpx;
  color: #007AFF;
  margin-top: 20rpx;
}

/* 第三方登录 */
.login-container .third-party-login {
  display: flex;
  align-items: center;
  margin: 60rpx 0 30rpx 0;
}

.login-container .third-party-login .line {
  flex: 1;
  height: 1rpx;
  background-color: #ddd;
}

.login-container .third-party-login .or-text {
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #999;
}

.login-container .third-party-icons {
  display: flex;
  justify-content: center;
  gap: 60rpx;
}

.login-container .third-party-icons .icon-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 24rpx;
  color: #666;
}

.login-container .third-party-icons .icon-wrapper .iconfont {
  font-size: 60rpx;
  margin-bottom: 10rpx;
}

</style>